package com.hmy.cornpestdet.service;

import com.hmy.cornpestdet.mapper.WarningSystemMapper;
import com.hmy.cornpestdet.pojo.User;
import com.hmy.cornpestdet.pojo.WarningSystem;
import com.hmy.cornpestdet.utils.CPDConst;
import com.hmy.cornpestdet.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class WarningSystemService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    WarningSystemMapper warningSystemMapper;

    public Result addWarningSystem(WarningSystem warningSystem) {
        WarningSystem temp = getWarningSystemByProvince(warningSystem.getProvince());
        //如果该省还未插入则插入，否则更新即可
        if(temp == null) {
            if(warningSystemMapper.addWarningSystem(warningSystem) > 0) {
                return Result.Success("发布成功",null);
            }
        }
        else{
            if(warningSystemMapper.updateWarningSystem(warningSystem) > 0) {
                return Result.Success("发布成功",null);
            }
        }
        return Result.Error("发布失败");


    }

    public int updateWarningSystem(WarningSystem warningSystem) {
        return warningSystemMapper.updateWarningSystem(warningSystem);
    }

    public WarningSystem getWarningSystemByProvince(String province) {
        return warningSystemMapper.getWarningSystemByProvince(province);
    }

    public WarningSystem getCurrentUserWarningSystem() {
        //获取当前的uid
        String uidStr = redisTemplate.opsForValue().get(CPDConst.CURRENT_USER_UID);
        if(uidStr == null){
            return null;
        }
        int uid = Integer.valueOf(uidStr);
        //拿到用户信息
        User user = getUserByUid(uid);
        //根据用户的省份返回预警信息
        return getWarningSystemByProvince(user.getProvince());
    }

    private User getUserByUid(int uid) {
        return warningSystemMapper.getUserByUid(uid);
    }
}
